﻿using System;
using System.Xml.Linq;
using PTop.Domain.ViewModel.Wechat;

namespace PTop.Front.Areas.Wechat.Models
{
    public class ImgMessage : WechatMsgBase
    {
        public string PicUrl { get; set; }
        public string MediaId { get; set; }
        public long MsgId { get; set; }

        /// <summary>
        /// 从xml数据加载文本消息
        /// </summary>
        /// <param name="xml"></param>
        public static ImgMessage LoadFromXml(string xml)
        {
            ImgMessage tm = null;
            if (!string.IsNullOrEmpty(xml))
            {

                XElement element = XElement.Parse(xml);
                if (element != null)
                {
                    tm = new ImgMessage();
                    tm.FromUserName = element.Element(WeChatCommon.FROM_USERNAME).Value;
                    tm.ToUserName = element.Element(WeChatCommon.TO_USERNAME).Value;
                    tm.CreateTime = element.Element(WeChatCommon.CREATE_TIME).Value;
                    tm.MsgId = long.Parse(element.Element(WeChatCommon.MSG_ID).Value);
                    tm.MediaId = element.Element("MediaId").Value;
                    tm.PicUrl = element.Element("PicUrl").Value;
                }
            }

            return tm;
        }
        public override string Template
        {
            get { throw new NotImplementedException(); }
        }

        private void ProcessRequest(object param)
        {
            try
            {
                var guid = param.ToString();
      
                //检测该openid是否存在guid,如果有则表示是微信传图模式,否则是普通的图片消息
                //WeChatWapBiz biz = new WeChatWapBiz();
                ////转换图片
                //var imgUrl = WeChatImgUploadHelper.Instance.ConvertImgUrl(this.PicUrl);
                ////保存图片信息
                //WeChatImgUploadEntity dto = new WeChatImgUploadEntity()
                //{
                //    CodeID = guid,
                //    ImgUrl = imgUrl,
                //    OpenID = FromUserName,
                //    MsgID = this.MsgId
                //};
                //var result = biz.InsertUploadImg(dto);
            }
            catch (Exception e)
            {
                //LogNet.Error("微信图片保存处理失败：" + param ?? "null", e);
                throw;
            }
        }

        public override string HandleRequest()
        {
            //WeChatWapBiz biz = new WeChatWapBiz();
            //var guid = biz.GetGuidByOpenID(this.FromUserName);
            //if (string.IsNullOrEmpty(guid))//普通的图片消息
            //{
            //    return "success";
            //}

            //Thread t = new Thread(ProcessRequest);
            //t.Start(guid);
            return "success";


        }

        public override string MsgType
        {
            get { return "msg"; }
        }
    }
}